#include "imaptaskthread.h"
#include "../../../11-util/02-log_manager/logmanager.h"
#include <QString>



static Logger * imapLogger = LogManager::getMissionLogger("__imap");
static QString TAG = "ImapTaskThread";

ImapTaskThread::ImapTaskThread(QObject *parent) {
    LogManager::debug("CreateImapParseThread","before");
    parseThread = new ImapParseThread(parent);
    parseThread->start();
    LogManager::debug("CreateImapParseThread","after");
}

/**
 * 如果socket断网,或者有一个命令出错,应该放弃整个队列.
 * TODO: 在执行一个任务时,如何关联一个函数,让外界/ui,显示一下更新,表明当前执行的进度?
 * TODO2: 如何写一个程序,向微信里发送一个消息?
 * @brief ImapTaskThread::run
 */
void ImapTaskThread::run()  {
    while(1){
        // qDebug() << "hello";

        if(taskQueue.length() == 0) {
            QThread::sleep(1);
            continue;
        }
        ImapTask * task = taskQueue.dequeue();
        this->executeTask(task);
    }
}

/**
 * 将任务加入到队列等待执行.
 * 是否有线程唤醒机制,替代sleep方式?
 * @brief ImapTaskThread::addTask
 * @param task
 */
void ImapTaskThread::addTask(ImapTask * task) {
    taskQueue.enqueue(task);
}

void ImapTaskThread::executeTask(ImapTask * task) {
    switch(task->type) {
    case ImapTaskType::Connect:{
        //连接任务
        QString fmt = "%1 connect to server %2 %3";
        LogManager::debug(fmt.arg(QString::number((long long)QThread::currentThreadId())).arg(this->imapServer).arg(QString::number(this->imapPort)),"ImapTaskThread");
        //如果传this会报错,因为this是主线程创建的,现在是一个子线程.
        this->mSocket = new QTcpSocket();
        this->mSocket->connectToHost(this->imapServer,this->imapPort);
        if(this->mSocket->waitForConnected()){
            qDebug() << "connnected";
            QString res = this->readSocketSync();
            task->rawResult = res;
            imapLogger->debug(TAG,"ReadSocketSync","After",res);
            parseThread->addTask(task);
        }
        else {
            qDebug() << "time out";
        }
        break;
    }
    default:{
        //非连接任务
        QString cmd = task->cmd;
        this->mSocket->write(cmd.toUtf8().constData());
        this->mSocket->flush();
        QString fmt("[C] [sending cmd:%1]");
        QString str = fmt.arg(cmd);
        imapLogger->debug(TAG,"ReadSocketSync","Before",str);
        QString ret = this->readSocketSync();
         imapLogger->debug(TAG,"ReadSocketSync","After",ret);
        task->rawResult = ret;
        parseThread->addTask(task);
        //socket超时,task执行失败.
        break;
    }
    }


}

QString ImapTaskThread::readSocketSync() {
    // -1 代表等待无限.
    QString ret = "";
    if(mSocket->waitForReadyRead(30000)) {
        QByteArray buffer = this->mSocket->readAll();
        ret = "" + buffer;
        QString fmt("[S] [receive res:%1]");
        QString info = fmt.arg(ret);
        qDebug() << info;
    }
    return ret;
}

